Skip to content

Fix #20429 — Attention layer hardcodes 3-D shape assumptions, breaking N-D inputs#22361

Draft
pctablet505 wants to merge 2 commits intokeras-team:masterfrom
pctablet505:fix/20429-attention-nd-inputs
Draft

Fix #20429 — Attention layer hardcodes 3-D shape assumptions, breaking N-D inputs#22361
pctablet505 wants to merge 2 commits intokeras-team:masterfrom
pctablet505:fix/20429-attention-nd-inputs

Conversation

@pctablet505
Copy link
Collaborator

Fixes: #20429
This pull request improves the flexibility and correctness of the Attention layer in Keras by updating how attention scores are computed and returned, particularly for inputs with more than 3 dimensions (N-D inputs). The changes ensure that the layer can seamlessly handle high-dimensional data, such as outputs from convolutional layers, and that attention score shapes are computed correctly. Additionally, new tests are added to verify this expanded support.

Enhancements to N-Dimensional Input Support:

  • Updated the computation of attention scores in _calculate_scores to use ops.swapaxes(key, -2, -1) instead of a fixed axes transpose, allowing for correct handling of N-D inputs.

  • Modified the calculation of the attention scores' output shape in both compute_output_shape and compute_output_spec to generalize over N-D inputs, using *query_shape[:-1] and key_shape[-2] for shape construction. [1] [2]

Testing Improvements:

  • Added a new test (test_attention_nd_inputs) to verify that the Attention layer correctly supports 4D inputs (such as those from Conv2D layers), including checks for both output and attention score shapes.

Problem

The Attention layer assumed inputs are exactly 3-D (batch, time, features). Two concrete failures:

  1. Score computation used ops.transpose(key, axes=[0, 2, 1]) — a hard-coded 3-D permutation. For any other rank this raises a shape error or silently produces wrong results.
  2. compute_output_shape and compute_output_spec built output shapes as (query_shape[0], query_shape[1], key_shape[1]) — again 3-D only. Calling model.predict() (which goes through compute_output_spec) on a model with Attention and 4-D inputs failed with a shape error.

Fix

  • Replace ops.transpose(key, axes=[0, 2, 1]) with ops.swapaxes(key, -2, -1) — works for any rank.
  • Replace fixed index shape tuples with variadic forms: (*query_shape[:-1], key_shape[-2]) for attention-score shape and (*query_shape[:-1], value_shape[-1]) for output shape.

Files Changed

  • keras/src/layers/attention/attention.py_calculate_scores, compute_output_shape, compute_output_spec
  • keras/src/layers/attention/attention_test.py — new test with 4-D inputs (batch, H, W, C), verifies output and score shapes

The Attention layer hardcoded axes=[0, 2, 1] in the transpose for dot
score calculation, which only works for 3D tensors. When 4D inputs
(e.g. from Conv2D/MaxPooling2D) are passed, it raises a dimension
mismatch error.

Replace ops.transpose(key, axes=[0, 2, 1]) with ops.swapaxes(key,
-2, -1) which generalizes to any number of dimensions. Also fix
compute_output_shape and compute_output_spec to use relative indices
instead of hardcoded positional indices.

Fixes keras-team#20429
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses a limitation in the Keras Attention layer where it incorrectly assumed 3-dimensional inputs, leading to errors or incorrect behavior with higher-dimensional data. The changes generalize the layer's internal operations and shape inference mechanisms to properly support N-dimensional inputs, such as those commonly produced by convolutional layers. This enhancement improves the layer's robustness and applicability across diverse model architectures, with new tests confirming the expanded functionality.

Highlights

  • N-D Input Support: The Attention layer now correctly handles N-dimensional inputs, resolving issues where it previously assumed a fixed 3-D shape.
  • Generalized Score Computation: Replaced a hardcoded 3-D transpose operation (ops.transpose(key, axes=[0, 2, 1])) with a flexible ops.swapaxes(key, -2, -1) for attention score calculation, ensuring compatibility with varying input ranks.
  • Dynamic Output Shape Inference: Updated compute_output_shape and compute_output_spec to dynamically infer output and attention score shapes using variadic forms (*query_shape[:-1]), accommodating N-D inputs beyond the previous 3-D assumption.
  • New Test Cases: Added test_attention_nd_inputs to validate the Attention layer's behavior with 4D inputs, including checks for both output and attention score shapes.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • keras/src/layers/attention/attention.py
    • Replaced ops.transpose(key, axes=[0, 2, 1]) with ops.swapaxes(key, -2, -1) in _calculate_scores for N-D input compatibility.
    • Updated scores_shape calculation in compute_output_shape from (query_shape[0], query_shape[1], key_shape[1]) to (*query_shape[:-1], key_shape[-2]).
    • Modified scores_shape calculation in compute_output_spec from fixed indices to (*query.shape[:-1], key.shape[-2]).
  • keras/src/layers/attention/attention_test.py
    • Added test_attention_nd_inputs to verify the Attention layer's behavior with 4D inputs, including output and attention score shape assertions.
Activity
  • No human activity (comments, reviews, etc.) has occurred on this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request correctly addresses an issue where the Attention layer was limited to 3-D inputs. The changes to use ops.swapaxes and more general shape computations in compute_output_shape and compute_output_spec are well-implemented and effectively enable support for N-D inputs. The addition of test_attention_nd_inputs provides good test coverage for this new capability.

As a suggestion for further improvement, the docstrings for the Attention layer and its methods still describe input and output shapes in terms of 3-D tensors (e.g., (batch_size, Tq, dim)). To align with the changes and improve user understanding, it would be beneficial to update these to reflect the new N-D support (e.g., (*batch_dims, Tq, dim)). This would be in line with the Keras API design guidelines on documentation.

@codecov-commenter
Copy link

codecov-commenter commented Mar 5, 2026

Codecov Report

❌ Patch coverage is 50.00000% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 82.95%. Comparing base (95e74a9) to head (257a451).

Files with missing lines Patch % Lines
keras/src/layers/attention/attention.py 50.00% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##           master   #22361   +/-   ##
=======================================
  Coverage   82.95%   82.95%           
=======================================
  Files         595      595           
  Lines       66040    66040           
  Branches    10305    10305           
=======================================
  Hits        54785    54785           
  Misses       8639     8639           
  Partials     2616     2616           
Flag Coverage Δ
keras 82.78% <50.00%> (ø)
keras-jax 60.83% <50.00%> (ø)
keras-numpy 55.03% <50.00%> (ø)
keras-openvino 49.10% <50.00%> (ø)
keras-tensorflow 62.06% <50.00%> (+<0.01%) ⬆️
keras-torch 60.87% <50.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@hertschuh
Copy link
Collaborator

@pctablet505

Is this ready for review? It's marked as draft right now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants